package north

import (
	"iot-base/common/cache"
	"iot-base/common/ctrltype"
	"strconv"
)

func init() {
	RegisterCtrlFun("queryData", func(pCmd *ctrltype.CtrlCmd) (map[string]interface{}, error) {
		params := pCmd.Params
		if params != nil {
			var stype, ssubid, spid string
			var pi = 0
			qtype, okType := params["type"]
			pid, okPid := params["pid"]
			subid, okSubid := params["subid"]
			sindex, okIndex := params["pi"]
			tid := pCmd.ThingID
			if okType {
				stype = qtype.(string)
			}
			if okSubid {
				ssubid = subid.(string)
			}
			if okPid {
				spid = pid.(string)
			}
			if okIndex {
				spi, ok := sindex.(string)
				if ok {
					pi, _ = strconv.Atoi(spi)
				} else {
					pi = sindex.(int)
				}
			}
			var datas interface{}
			var err error
			var result map[string]interface{}
			if spid != "" {
				if stype == "hour" {
					datas, err = cache.GetIntegralHourDatas(tid, spid, ssubid, pi)
				} else {
					datas, err = cache.GetLastValues(tid, spid, ssubid, pi)
				}

			} else {
				datas, err = cache.GetThingView(tid)
			}
			if datas != nil {
				result = make(map[string]interface{})
				result["datas"] = datas
			}
			return result, err
		}
		return nil, nil
	})
}
